<script setup>
import { onMounted, reactive, ref, watch, watchEffect, toRefs, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import
{
    Document,
    Setting,
    ArrowRightBold,
    ArrowLeftBold,
    Discount,
    SwitchButton,
    CircleCheck,
    VideoCamera,
    ChatDotSquare,
    User,
    House,
    Search,
    ChatLineSquare,
    More,
    CaretBottom,
    Minus,
    Close
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useTabsStore } from '../store/store.js';
import { userAndUserType, findUserById } from '../api/user'
import { userTypeFindByName } from "../api/usertype"
import { getAccount, getAvatarUrl, removeAll } from "../utils/auth";
import HomePage from "../components/index.vue"

import { messageCreate, messageRead } from "../api/message/message";
const useData = useTabsStore()

const route = useRoute();
const router = useRouter();
const isCollapse = ref(true)
const handleOpen = (key, keyPath) =>
{
    console.log(key, keyPath)
}
const handleClose = (key, keyPath) =>
{
    console.log(key, keyPath)
}

// 点击侧标栏菜单
const clickItem = (item) =>
{
    tabsData.activeTab = item;
    console.log(item, "标签");
}


const breadcrumbItems = computed(() =>
{
    const matchedRoutes = route.matched;
    const items = [{ text: '首页', link: '/homePage' }];

    // 添加当前子页面的导航项到面包屑导航
    matchedRoutes.forEach((r) =>
    {
        if (r.path != '/homePage' && r.path != '/home') {
            items.push({ text: r.meta.title, link: r.path });
        }
    });
    if (items.length > 1) {
        // 剔除第一个导航项
        items.shift();
    }

    return items;
});

// 动态改变面包屑导航
onMounted(async () =>
{
    console.log(useData.getUserData().userName, "1111111");
    userAndUserType({ "username": useData.getUserData().userName }).then(res =>
    {
        const userTypeName = res.data.UserType.UserTypeName;
        userTypeFindByName({ "userTypeName": userTypeName }).then(resType =>
        {
            console.log(resType);
            state.menuItems = resType.data.Resources
        }).catch(errType =>
        {
            console.log(errType);
        })
        console.log(userTypeName);
    }).catch(err =>
    {
        console.log(err);
    })
})




const tabsStore = useTabsStore();
const tabsData = reactive({
    ...toRefs(tabsStore)
})

// 防止出现多个弹窗
const dropdownRef = ref()
const handleChange = (visible, name) =>
{
    if (!visible) return
    dropdownRef.value.forEach(item =>
    {
        if (item.id === name) return
        item.handleClose()
    })
}
// 关闭所有标签页面
const closeTabAll = () =>
{
    tabsStore.removeAllTab()
    router.push('/homePage')
}
// 标签栏
const handleTabRemove = (tabName) =>
{
    const index = tabsData.tabs.findIndex(tab => tab.path === tabName);
    if (index !== -1) {
        tabsStore.removeTab(index);
        if (router.currentRoute.value.path === tabName) {
            const nextTab = tabsData.tabs[index] || tabsData.tabs[index - 1];
            tabsData.activeTab = nextTab.path;
            console.log(nextTab, "下一个标签栏");
            if (nextTab) {
                router.push(nextTab.path);
            } else {
                tabsData.activeTab = '/home';
                router.push('/home');
            }
        }
    }
}

// 点击tab
const clickTab = (tab) =>
{
    console.log(tab.paneName);
    console.log(tabsData.tabs, '存储的标签');
    router.push(tab.paneName)
}


const stateData = ref('')
const links = ref([])
const state = reactive({
    nowDate: "2023-09-01",
    nowTime: "12:00:00",
    nowWeek: "星期一",
    weekArr: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    routerList: [],
    // 菜单栏
    menuItems: [],
    userInfo: {
        avatarUrl: '',
        fullName: ''
    }
})

// const loadAll = () =>
// {
//     return [
//         { value: 'vue', link: 'https://github.com/vuejs/vue' },
//         { value: 'element', link: 'https://github.com/ElemeFE/element' },
//         { value: 'cooking', link: 'https://github.com/ElemeFE/cooking' },
//         { value: 'mint-ui', link: 'https://github.com/ElemeFE/mint-ui' },
//         { value: 'vuex', link: 'https://github.com/vuejs/vuex' },
//         { value: 'vue-router', link: 'https://github.com/vuejs/vue-router' },
//         { value: 'babel', link: 'https://github.com/babel/babel' },
//     ]
// }

// let timeout
// // 触发过滤条件
// const querySearchAsync = (queryString, cb) =>
// {
//     const results = queryString
//         ? links.value.filter(createFilter(queryString))
//         : links.value

//     clearTimeout(timeout)
//     timeout = setTimeout(() =>
//     {
//         cb(results)
//     }, 3000 * Math.random())
// }
// // 创建过滤
// const createFilter = (queryString) =>
// {
//     return (restaurant) =>
//     {
//         return (
//             restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
//         )
//     }
// }
// // 搜索框选择
// const handleSelect = (item) =>
// {
//     console.log(item)
// }
// 跳转
const toPage = (path) =>
{
    // 传递数值并跳转
    router.push(path);
}
const getMessageLength = async () =>
{
    const result = await messageRead({ messageStatus: 1, pagination: false })
    if (result.meta.status === 200) {
        state.messageLength = result.data.readResult.filter(item => { return item.user_id === useData.getUserData().userID }).length
    }
}
// 获取用户信息
const getUserInfo = async () =>
{
    const resultByID = await findUserById({ userId: tabsData.getUserData().userID })
    console.log(resultByID, "<===========");
    state.userInfo.avatarUrl = resultByID.data.Avatar
    state.userInfo.fullName = resultByID.data.FullName
}

onMounted(() =>
{
    // links.value = loadAll()
    updateNowDate();
    setInterval(updateNowTime, 1000);
    updateNowWeek();
    getMessageLength()
    getUserInfo()

})
// 更新时间
const updateNowDate = () =>
{
    state.nowDate = new Date().toISOString().slice(0, 10);
}
const updateNowTime = () =>
{
    state.nowTime = new Date().toLocaleTimeString({ hour12: false });
}
const updateNowWeek = () =>
{
    state.nowWeek = state.weekArr[new Date().getDay()];
}
const toSetting = () =>
{
    router.push('/Setting')
}
//退出
const loginOut = () =>
{
    ElMessageBox.confirm(
        '确定需要退出系统登录吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() =>
        {
            messageCreate({ userId: useData.getUserData().userID, message: `${useData.getUserData().userName}用户 退出登录`, operationType: 'message' }).then(() =>
            {
                ElMessage({
                    type: 'success',
                    message: '已退出',
                })
                removeAll()
                router.push('/login')
            })
        })
        .catch(() =>
        {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })

}

</script>
<template>
    <div class="common-layout">
        <el-container class="min-h-screen">
            <el-aside width="auto" class="bg-gray-800">
                <div class="pt-8 pb-8 pr-14 pl-14 text-center bg-gray-800 flex justify-center flex-col items-center"
                    v-if="!isCollapse">
                    <img src="../assets/ifont/pic/logo.jpg" alt="logo" class="w-24 h-24 mb-4">
                    <div class=" text-white">工单管理系统</div>
                </div>

                <el-menu :default-active="$route.path" @select="clickItem" class="el-menu-vertical-demo" :router="true"
                    :collapse="isCollapse" @open="handleOpen" @close="handleClose" background-color="#1F2937"
                    text-color="#dfe2db">
                    <template v-for="item in state.menuItems" :key="item.id">
                        <el-menu-item :index="item.MainMenuURL" v-if="item.HasChild == 0" class="mb-1">
                            <i :class="'iconfont ' + item.MainMenuIcon" class="pr-2" />
                            <template #title>{{ item.MainMenuName }}</template>
                        </el-menu-item>
                        <el-sub-menu :index="item.MainMenuURL" v-else class="mb-1">
                            <template #title>
                                <i :class="'iconfont ' + item.MainMenuIcon" class="pr-2" />
                                <span>{{ item.MainMenuName }}</span>
                            </template>
                            <el-menu-item-group>
                                <el-menu-item :index="subItem.Path" v-for="(subItem, index) in item.SubMenuInfo"
                                    :key="index">
                                    <i :class="'iconfont ' + subItem.Icon" class="pr-2" />
                                    {{ subItem.ResourceName }}
                                </el-menu-item>
                            </el-menu-item-group>
                        </el-sub-menu>
                    </template>
                </el-menu>
            </el-aside>

            <el-container>
                <el-header class="bg-gray-800 flex items-center">
                    <div class="w-full">
                        <el-radio-group v-model="isCollapse">
                            <el-radio-button :label="false" v-if="isCollapse">
                                <el-icon>
                                    <ArrowRightBold />
                                </el-icon>
                            </el-radio-button>
                            <el-radio-button :label="true" v-else>
                                <el-icon>
                                    <ArrowLeftBold />
                                </el-icon>
                            </el-radio-button>
                        </el-radio-group>
                        <!-- <el-col :span="4"></el-col> -->
                        <div class="flex items-baseline float-right">
                            <!-- 如果是移动端则不显示下面的这些 -->
                            <div class="flex items-end text-white flex-row-reverse">
                                <div class="h-full pr-2">{{ state.nowDate }}</div>
                                <div class="h-full pr-2 text-3xl">{{ state.nowTime }}</div>
                                <div class="h-full pr-2">{{ state.nowWeek }}</div>
                            </div>
                            <!-- <el-col :span="8" class="flex flex-row-reverse pr-2"> -->
                            <!-- <el-autocomplete v-model="stateData" :fetch-suggestions="querySearchAsync" placeholder="请输入关键字"
                                @select="handleSelect">
                                <template #suffix>
                                    <el-icon color="#000">
                                        <Search />
                                    </el-icon>
                                </template>
                                <template #append>
                                    <el-button type="primary">搜索</el-button>
                                </template>
                            </el-autocomplete> -->

                            <div class="flex items-end h-full pl-2">
                                <!-- 头像 -->
                                <div class="flex m-2">
                                    <div class="flex flex-col h-full justify-center">
                                        <el-avatar :size="40" :src="getAvatarUrl(state.userInfo.avatarUrl)" />
                                    </div>
                                </div>
                                <!-- 头像顶部信息 -->
                                <div class="flex justify-center items-center pb-1 text-[#dde2db] mr-8">
                                    <div class="pl-2 text-lg mr-6">晚上好,{{ state.userInfo.fullName }}</div>
                                    <el-dropdown trigger="click">
                                        <span class="el-dropdown-link  text-[#c6c8c5]">
                                            更多
                                            <el-icon>
                                                <CaretBottom />
                                            </el-icon>
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item>
                                                    <div class="flex items-center text-sm cursor-pointer hover:font-bold"
                                                        @click="toPage('/Message')">
                                                        <el-icon color="green" class="font-blod">
                                                            <ChatLineSquare />
                                                        </el-icon>
                                                        <i class="pl-1 text-[#dde2db] not-italic">消息</i>
                                                    </div>
                                                    <el-badge class="mark" :value="state.messageLength"
                                                        v-if="state.messageLength !== 0" />
                                                </el-dropdown-item>
                                                <el-dropdown-item>
                                                    <div class="flex items-center mt-2 text-sm cursor-pointer"
                                                        @click="toSetting">
                                                        <el-icon color="blue" class="font-blod">
                                                            <Setting />
                                                        </el-icon>
                                                        <i class="pl-1 text-[#dde2db] not-italic">设置</i>
                                                    </div>
                                                </el-dropdown-item>
                                                <el-dropdown-item>
                                                    <div class="flex items-center mt-2 text-sm cursor-pointer"
                                                        @click="loginOut">
                                                        <el-icon color="red" class="font-blod">
                                                            <SwitchButton />
                                                        </el-icon>
                                                        <i class="pl-1 text-[#dde2db] not-italic pr-6">注销</i>
                                                    </div>
                                                </el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-header>
                <el-main class=" bg-slate-100">
                    <div class="pt-5 pl-5 pr-5 rounded-lg">
                        <!-- <div class="mb-1 rounded-lg">
                            <el-breadcrumb separator="/">
                                <el-breadcrumb-item v-for="item in breadcrumbItems" :key="item.path">
                                    {{ item.text }}
                                </el-breadcrumb-item>
                            </el-breadcrumb>
                        </div> -->
                        <el-tabs v-model="tabsData.activeTab" @tab-click="clickTab" type="card"
                            @tab-remove="handleTabRemove">
                            <!-- 使用 :closable="item.closable" 控制关闭按钮的显示 -->
                            <el-tab-pane v-for="(item, index) in tabsData.tabs" :key="item.path" :label="item.meta.title"
                                :name="item.path" :closable="item.closable" :index="index">
                                <template #label>
                                    <el-dropdown trigger="contextmenu" ref="dropdownRef"
                                        @visible-change="handleChange($event, item.meta.title)" :id="item.meta.title">
                                        <span :class="tabsData.activeTab == item.path ? 'text-blue-400' : ''">
                                            {{ item.meta.title }}
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item @click="handleTabRemove(item.path)">
                                                    <el-icon>
                                                        <Close />
                                                    </el-icon>关闭当前</el-dropdown-item>
                                                <el-dropdown-item @click="closeTabAll">
                                                    <el-icon>
                                                        <Minus />
                                                    </el-icon>关闭所有</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </template>
                            </el-tab-pane>
                        </el-tabs>
                        <router-view />
                    </div>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>
<style lang="scss" scoped>
.el-main {
    padding: 0;
}

:deep .el-popover {
    padding: 0;
}

:deep .el-tabs__header {
    margin: 0;
    padding: 0;
}
</style>